﻿/*
 * Copyright(C) 2012,ajayumi 保留所有权利。( All rights reserved. )
 * 
 * 文件名称：JQueryGrid.cs
 * 摘    要：
 * 当前版本：1.0
 * 作    者：黄乙冬 (ajayumi)
 * 创建日期：2012年6月1日星期五
 */
using System;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;
using ajayumi.Platform.Core.Security;

namespace ajayumi.Platform.Web.Controls.DataGrid
{
    /// <summary>
    /// 将 JqGrid 进行封装
    /// </summary>
    [ToolboxData("<{0}:JQueryGrid runat=\"server\"> </{0}:JQueryGrid>")]
    public class JQueryGrid : WebControl
    {
        private readonly static CryptoProvider m_CryptoProvider = ProviderFactory.CreateCryptoProvider();

        #region Properties

        #region 基本参数
        //每页显示行数默认50
        private int _rowNum = 10;
        [Description("每页显示行数")]
        public int RowNum
        {
            get { return _rowNum; }
            set { _rowNum = value; }
        }

        //排序字段默认id
        private string _sortName = "Id";
        [Description("排序字段")]
        public string SortName
        {
            get { return _sortName; }
            set { _sortName = value; }
        }

        //排序顺序
        private string _sortOrder = "desc";
        [Description("排序字段")]
        public string SortOrder
        {
            get { return _sortOrder; }
            set { _sortOrder = value; }
        }

        //是否显示总数量，默认是
        private bool _viewRecords = true;
        [Description("显示总数量")]
        public bool ViewRecords
        {
            get { return _viewRecords; }
            set { _viewRecords = value; }
        }

        //是否使用滚动条翻页，默认否
        private bool _scrollabled = false;
        [Description("是否使用滚动条翻页")]
        public bool Scrollabled
        {
            get { return _scrollabled; }
            set { _scrollabled = value; }
        }

        //每页显示行数选择
        private string _rowList = "[10,20,50]";
        [Description("每页显示行数选择，格式：[10,20,50]")]
        public string RowList
        {
            get { return _rowList; }
            set { _rowList = value; }
        }

        //是否显示行号，默认是
        private bool _rowNumberabled = false;
        [Description("是否显示行号")]
        public bool RowNumberabled
        {
            get { return _rowNumberabled; }
            set { _rowNumberabled = value; }
        }

        //行号宽度默认30
        private int _rowNumWidth = 30;
        [Description("行号宽度")]
        public int RowNumWidth
        {
            get { return _rowNumWidth; }
            set { _rowNumWidth = value; }
        }

        //表格高度默认0
        private int _height = 0;
        [Description("表格高度")]
        public int GridHeight
        {
            get { return _height; }
            set { _height = value; }
        }

        //表格名称
        private string _caption = string.Empty;
        [Description("表格名称，如果为空则不显示表格名称行")]
        public string Caption
        {
            get { return _caption; }
            set { _caption = value; }
        }
        //多选，默认否
        private bool _multiSelectabled = true;
        [Description("多选，默认否")]
        public bool MultiSelectabled
        {
            get { return _multiSelectabled; }
            set { _multiSelectabled = value; }
        }

        private string constructorAssembly = "App_Code";
        [Description("JQueryGridConstructor 构造器 Assembly")]
        public string ConstructorAssembly
        {
            get
            { return this.constructorAssembly; }
            set
            { this.constructorAssembly = value; }
        }

        private string constructorName = string.Empty;
        [Description("JQueryGridConstructor 构造器 Name")]
        public string ConstructorName
        {
            get
            { return this.constructorName; }
            set
            { this.constructorName = value; }
        }

        [Description("数据处理的Handler")]
        public string AjaxDataHandler { get; set; }

        #endregion

        #region 动作按钮
        [Description("查询方式，默认无")]
        public JGridOpMode SearchMode
        {
            get;
            set;
        }
        [Description("添加方式，默认无")]
        public JGridOpMode AddMode
        {
            get;
            set;
        }
        [Description("编辑方式，默认无")]
        public JGridOpMode EditMode
        {
            get;
            set;
        }
        [Description("删除方式，默认无")]
        public JGridOpMode DeleteMode
        {
            get;
            set;
        }
        #endregion


        #endregion

        public JQueryGrid()
        {
            this.SearchMode = JGridOpMode.None;
            this.AddMode = JGridOpMode.None;
            this.EditMode = JGridOpMode.None;
            this.DeleteMode = JGridOpMode.None;
        }

        protected override void OnPreRender(EventArgs e)
        {
            this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
            base.OnPreRender(e);
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(this.BuildJqGridHtml());
            sb.AppendFormat("\n<table id=\"{0}Table\"></table>\n", this.ID);
            sb.AppendFormat("<div id=\"{0}Pager\"></div>\n", this.ID);
            //sb.AppendFormat("<div id=\"{0}JQueryDlg\">{1}</div>\n", this.ID, this.GetForms());
            //sb.AppendFormat("<div id=\"{0}JQueryDlg\"></div>\n", this.ID);
            //sb.Append(this.GetForms());
            writer.Write(sb.ToString());
        }

        /// <summary>
        /// 向页面注册css和js
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            HtmlLink jqGridStyle1 = new HtmlLink();
            jqGridStyle1.Attributes["type"] = "text/css";
            jqGridStyle1.Attributes["rel"] = "stylesheet";
            jqGridStyle1.Attributes["href"] = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.css.ui.jqgrid.css");
            this.Page.Header.Controls.Add(jqGridStyle1);
            HtmlLink jqGridStyle2 = new HtmlLink();
            jqGridStyle2.Attributes["type"] = "text/css";
            jqGridStyle2.Attributes["rel"] = "stylesheet";
            jqGridStyle2.Attributes["href"] = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.searchFilter.css");
            this.Page.Header.Controls.Add(jqGridStyle2);
            HtmlLink jqGridStyle3 = new HtmlLink();
            jqGridStyle3.Attributes["type"] = "text/css";
            jqGridStyle3.Attributes["rel"] = "stylesheet";
            jqGridStyle3.Attributes["href"] = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.ui.multiselect.css");
            this.Page.Header.Controls.Add(jqGridStyle3);

            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.js.i18n.grid.locale-cn.js");
            //this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.js.i18n.grid.locale-en.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.js.jquery.jqGrid.min.js");
            //this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.js.jquery.jqGrid.src.js");

            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.grid.addons.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.grid.postext.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.grid.setcolumns.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.jquery.contextmenu.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.jquery.searchFilter.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.jquery.tablednd.js");
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "ajayumi.Platform.Web.Controls.DataGrid.JqGrid.plugins.ui.multiselect.js");

        }

        /// <summary>
        /// 构造jqGrid页面JS，主体功能
        /// </summary>
        /// <returns></returns>
        private string BuildJqGridHtml()
        {
            JQueryGridConstructor constructor = null;

            StringBuilder sb = new StringBuilder();
            sb.Append("\n<script type=\"text/javascript\">\n");
            sb.Append("$(function(){\n");

            //-----------------------------------------------jqGrid js构造开始
            sb.AppendFormat("$(\"#{0}Table\").jqGrid({{\n", this.ID);
            sb.AppendFormat("url:\"{0}?action={1}\",\n", this.AjaxDataHandler, m_CryptoProvider.Encrypt(Operation.Read.ToString()));
            sb.Append("datatype: \"json\",\n");
            sb.AppendFormat("rowNum: {0},\n", this.RowNum);
            sb.AppendFormat("pager: '#{0}Pager',\n", this.ID);
            sb.AppendFormat("sortname: '{0}',\n", this.SortName);
            sb.AppendFormat("sortorder: '{0}',\n", this.SortOrder);
            sb.Append("viewrecords: true,\n");
            if (Scrollabled)
            {
                sb.Append("scroll: 1,\n");
            }
            else
            {
                sb.Append("rowList:" + RowList + ",\n");
            }
            if (RowNumberabled)
            {
                sb.Append("rownumbers: true,\n");
                sb.Append("rownumWidth: " + RowNumWidth + ",\n");
            }
            sb.AppendFormat("height: \"{0}\",\n", this.GridHeight <= 0 ? "auto" : this.GridHeight.ToString());
            sb.AppendFormat("autowidth: {0},\n", "true");
            if (!string.IsNullOrEmpty(Caption))
            {
                sb.AppendFormat("caption:'{0}',\n", this.Caption);
            }
            sb.AppendFormat("multiselect: {0},\n", this.MultiSelectabled.ToString().ToLower());
            sb.AppendFormat("editurl:'{0}?action={1}',\n", this.AjaxDataHandler, m_CryptoProvider.Encrypt(Operation.Update.ToString()));

            #region colModel构造开始，由配置文件完成
            sb.Append("colModel:[\n");
            if (!DesignMode)
            {
                if (string.IsNullOrEmpty(this.ConstructorAssembly))
                { throw new NotSupportedException("ConstructorAssembly 不能为空"); }
                if (string.IsNullOrEmpty(this.ConstructorName))
                { throw new NotSupportedException("ConstructorName 不能为空"); }
                if (string.IsNullOrEmpty(this.AjaxDataHandler))
                { throw new NotSupportedException("AjaxDataHandler 不能为空"); }

                constructor = (JQueryGridConstructor)Assembly.Load(this.ConstructorAssembly).CreateInstance(this.ConstructorName);
                sb.Append(constructor.GetColumnsModel());
            }
            sb.Append("],\n");
            #endregion

            sb.Append("gridview:true\n");
            sb.Append("});\n");
            //底部按钮自定义
            sb.AppendFormat("$(\"#{0}Table\").jqGrid('navGrid','#{0}Pager',{{", this.ID);
            sb.AppendFormat("search: {0},", (this.SearchMode == JGridOpMode.Default) ? "true" : "false");
            sb.AppendFormat("add: {0},", (this.AddMode == JGridOpMode.Default) ? "true" : "false");
            sb.AppendFormat("edit: {0},", (this.EditMode == JGridOpMode.Default) ? "true" : "false");
            sb.AppendFormat("del: {0},", (this.DeleteMode == JGridOpMode.Default) ? "true" : "false");
            sb.Append("refresh: true,");
            sb.Remove(sb.Length - 1, 1);
            sb.Append("},\n");
            #region use default settings for edit
            sb.Append("{");
            sb.Append("},\n");
            #endregion
            #region use default settings for add
            sb.Append("{");
            sb.Append("},\n");
            #endregion
            #region delete instead that del:false we need this
            sb.Append("{");
            sb.Append("},\n");
            #endregion
            #region enable the advanced searching
            sb.Append("{");
            sb.Append("multipleSearch:true,");
            sb.Append("closeAfterSearch:true,");
            sb.Append("closeOnEscape:true,");
            sb.Append("loadDefaults:true,");
            sb.Append("showQuery:true,");
            sb.AppendFormat("sopt: [{0}]", constructor.GetSoptString());
            sb.Append("}");
            #endregion
            sb.Append(");\n");

            #region Unused
            
            //caption：按钮名称，可以为空，string类型 
            //buttonicon：按钮的图标，string类型，必须为UI theme图标 
            //onClickButton：按钮事件，function类型，默认null 
            //position：first或者last，按钮位置 
            //title：string类型，按钮的提示信息 
            //cursor：string类型，光标类型，默认为pointer 
            //id：string类型，按钮id 
            //sb.AppendFormat("var dlg = $(\"#{0}JQueryDlg\");\n", this.ID);
            ////sb.Append("dlg.dialog({autoOpen: false});");
            //if (this.AddMode == JGridOpMode.Custom)
            //{
            //    sb.AppendFormat("$(\"#{0}Table\").jqGrid('navButtonAdd','#{0}Pager',{{", this.ID);
            //    sb.Append("caption: \"\",");
            //    //sb.Append("title: \"addCaption\",");
            //    sb.Append("buttonicon:\"ui-icon-plus\",");
            //    sb.Append("onClickButton: function (){");
            //    ////sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('editGridRow',\"new\",{{ }});", this.ID);
            //    //sb.AppendFormat("dlg.html('{0}');", this.GetForms());
            //    ////sb.AppendFormat("dlg.html('{0}');", "<span style=\"color: red;\">ajayumi</span>");
            //    //sb.AppendFormat("dlg.dialog({{ modal: true, title: '{0}', ", "添加记录");
            //    //sb.Append("buttons: [{ text: '确定', click: function(){ ");
            //    //sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('FormToGrid',1,\"#person\");", this.ID);
            //    //sb.Append("dlg.remove(); } }, ");
            //    //sb.Append("{ text: '取消', click: function(){ dlg.remove(); } }], ");
            //    //sb.Append("close: function (event, ui) { dlg.remove(); }");
            //    //sb.Append("});");
            //    sb.Append("}");
            //    sb.Append("});\n");
            //    //jQuery("#editgrid").jqGrid('editGridRow',"new",{height:280,reloadAfterSubmit:false});
            //}

            //if (this.EditMode == JGridOpMode.Custom)
            //{
            //    sb.AppendFormat("$(\"#{0}Table\").jqGrid('navButtonAdd','#{0}Pager',{{", this.ID);
            //    sb.Append("caption: \"\",");
            //    //sb.Append("title: \"editCaption\",");
            //    sb.Append("buttonicon:\"ui-icon-pencil\",");
            //    sb.Append("onClickButton: function (){");
            //    sb.AppendFormat("var gr = jQuery(\"#{0}Table\").jqGrid('getGridParam','selrow');", this.ID);
            //    sb.Append("if( gr != null ){");
            //    //sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('editGridRow',gr,{{ }});", this.ID);
            //    //sb.Append("dlg.dialog( \"open\" );");
            //    sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('GridToForm',gsr,\"#person\");", this.ID);
            //    //sb.AppendFormat("dlg.dialog({{ modal: true, title: '{0}', ", "修改记录");
            //    //sb.Append("buttons: [{ text: '确定', click: function(){ ");
            //    //sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('FormToGrid',1,\"#person\");", this.ID);
            //    //sb.Append("dlg.remove(); } }, ");
            //    //sb.Append("{ text: '取消', click: function(){ dlg.remove(); } }], ");
            //    //sb.Append("close: function (event, ui) { dlg.remove(); }");
            //    //sb.Append("});");
            //    sb.Append("}else alert(\"请选择记录\");");
            //    sb.Append("}");
            //    sb.Append("});");
            //    //var gr = jQuery("#editgrid").jqGrid('getGridParam','selrow');
            //    //if( gr != null ) jQuery("#editgrid").jqGrid('editGridRow',gr,{height:280,reloadAfterSubmit:false});
            //    //else alert("Please Select Row");

            //}

            #endregion

            #region 选择列
            //sb.AppendFormat("$(\"#{0}Table\").jqGrid('navButtonAdd','#{0}Pager',{{", this.ID);
            //sb.Append("caption: \"选择列\",");
            //sb.Append("title: \"Reorder Columns\",");
            //sb.Append("onClickButton : function (){");
            //sb.AppendFormat("jQuery(\"#{0}Table\").jqGrid('columnChooser');", this.ID);
            //sb.Append("}");
            //sb.Append("});");
            #endregion


            //-----------------------------------------------jqGrid js构造结束
            sb.Append("});\n");
            sb.Append("</script>");
            return sb.ToString();

        }

        private string GetForms()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<form method=\"post\" name=\"person\" id=\"person\" action=\"\" title=\"\" style=\"margin:0px;\">");
            sb.Append("<fieldset>");
            sb.Append("<legend>Data</legend>");
            sb.Append("<table>");
            sb.Append("<tbody>");
            sb.Append("<tr>");
            sb.Append("<td>Id: </td>");
            sb.Append("<td><input type=\"text\" name=\"Id\" readonly=\"true\" id=\"Id\" width=\"100%\" /></td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td>Code: </td>");
            sb.Append("<td><input type=\"text\" name=\"Code\"/></td>");
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td>Name: </td>");
            sb.Append("<td><input type=\"text\" name=\"Name\"/></td>");
            sb.Append("</tr>");
            sb.Append("</tbody>");
            sb.Append("</table>");
            sb.Append("</fieldset>");
            sb.Append("</form>");
            return sb.ToString();
        }




    }
}
